<template>
  <div>
    <el-table
      :data="tableData"
      ref="tableRef"
      @selection-change="handleSelectionChange"
      style="width: 100%"
      :row-key="row => row.id"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
    </el-table>
    <el-button @click="handleSelectAll">全选</el-button>
    <el-button @click="handleClearSelection">清空选择</el-button>
    <div>已选择的行数据: {{ selectedRows }}</div>
  </div>
</template>

<script setup>
import { ref } from "vue"

// 定义表格数据
const tableData = ref([
  { id: 1, name: "张三", age: 20, address: "北京市" },
  { id: 2, name: "李四", age: 25, address: "上海市" },
  { id: 3, name: "王五", age: 30, address: "广州市" },
  { id: 4, name: "赵六", age: 35, address: "深圳市" }
])

// 定义表格引用
const tableRef = ref(null)

// 定义选中行数据
const selectedRows = ref([])

// 处理选择变化的方法
const handleSelectionChange = val => {
  selectedRows.value = val
}

// 全选方法
const handleSelectAll = () => {
  tableRef.value?.toggleAllSelection()
}

// 清空选择方法
const handleClearSelection = () => {
  tableRef.value?.clearSelection()
}
</script>

<style scoped>
/* 可根据需求添加自定义样式 */
</style>
